#include <iostream>
using namespace std;

typedef struct
{
    int J; // weight
    int F; // price
    bool visited;
} room;

room rooms[1000];
int max_bought = 0;
int M, N;

void dfs(int remain, int bought)
{
    if (remain < 0)
    {
        return;
    }
    if (bought > max_bought)
    {
        max_bought = bought;
    }
    for (int i = 0; i < N; i++)
    {
        if (rooms[i].visited != true)
        {
            rooms[i].visited = true;
            dfs(remain - rooms[i].F, bought + rooms[i].J);
            rooms[i].visited = false;
        }
    }
    return;
}

int main()
{
    ios::sync_with_stdio(false);
    while (cin >> M >> N)
    {
        max_bought = 0;
        if (M == -1 && N == -1)
        {
            break;
        }
        for (int i = 0; i < N; i++)
        {
            cin >> rooms[i].J >> rooms[i].F;
        }
        dfs(M, 0);
        cout << max_bought << endl;
    }
    return 0;
}